
const Sequelize = require('sequelize');
const config = require('./config');

const sequelize = new Sequelize(config.database, config.username, config.password, {
    host: config.host,
    dialect: 'mysql',
    pool: {
        max: 5,
        min: 0,
        idle: 30000
    }
});

const Pet = sequelize.define('pet', {
    id: {
        type: Sequelize.STRING(50),
        primaryKey: true
    },
    name: Sequelize.STRING(100),
    gender: Sequelize.BOOLEAN,
    birth: Sequelize.STRING(10),
    createdAt: Sequelize.BIGINT,
    updatedAt: Sequelize.BIGINT,
    version: Sequelize.BIGINT
}, {
    timestamps: false
});

let now = Date.now();

const fnInsert1 = () => {
    Pet.create({
        id: 'g-' + now,
        name: 'Gaffey',
        gender: false,
        birth: '2007-07-07',
        createdAt: now,
        updatedAt: now,
        version: 0
    }).then((p) => {
        console.log('created. ' + JSON.stringify(p));
        sequelize.close();
    }).catch((err) => {
        console.error('failed: ', err);
    });
};

// fnInsert1();

const fnInsert2 = () => {
    (async () => {
        let dog = await Pet.create({
            id: 'd-' + now,
            name: 'Odie',
            gender: false,
            birth: '2008-08-08',
            createdAt: now,
            updatedAt: now,
            version: 0
        });
        console.log('created. ' + JSON.stringify(dog));
        sequelize.close();
    })();
};

// fnInsert2();

const fnQuery = () => {
    (async () => {
        const pets = await Pet.findAll({
            where: {
                name: 'Gaffey'
            }
        });
        console.log(`find ${pets.length} pets: `);
        for (let p of pets) {
            console.log(JSON.stringify(p));
        }
        sequelize.close();
    })();
};

fnQuery();


